package com.cdivtc.management.aspect;

import com.cdivtc.management.pojo.Result;
import com.cdivtc.management.service.LogSever;
import com.cdivtc.management.service.RequestServer;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * @author Promise
 * @createTime 2018年12月18日 下午9:33:28
 * @description 切面日志配置
 */
@Aspect
@Component
public class LoginUserLogAsPect {

    private final static Logger log = org.slf4j.LoggerFactory.getLogger(LoginUserLogAsPect.class);

    @Autowired
    private RequestServer requestServer;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private LogSever logSever;


    //表示匹配带有自定义注解的方法
    @Pointcut("@annotation(com.cdivtc.management.aspect.LoginUserLog)")

    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();

        try {
            log.info("我在目标方法之前执行！");
            result = point.proceed();

            long endTime = System.currentTimeMillis();
            insertLog(point, endTime - beginTime);
            Cookie[] cookies = request.getCookies();
            System.out.println("cookies = " + cookies);
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            log.info("我登录失败！");
//            用户登录失败
            try {
                long endTime = System.currentTimeMillis();
                logSever.loginError(request, endTime - beginTime);
                Result result1 = new Result();
                result1.error(e.getMessage());
                requestServer.SendReresponse(response, result1);
            } catch (IOException ex) {
                log.info("我登录失败！2");
            }
//            发起网络请求  获取ip实际地址


        }
        return result;
    }

    private void insertLog(ProceedingJoinPoint point, long time) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
//        登录日志


        LoginUserLog userAction = method.getAnnotation(LoginUserLog.class);
        if (userAction != null) {
            // 注解上的描述
            userAction.value();
        }

        // 请求的类名
        String className = point.getTarget().getClass().getName();
        // 请求的方法名
        String methodName = signature.getName();
        // 请求的方法参数值
        String args = Arrays.toString(point.getArgs());
        logSever.loginSuccess(request, time);

    }


}